import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXResult;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;

class XSLTPipe {

	public static void main(String[] args) throws Exception
	{
		TransformerFactory tFactory = TransformerFactory.newInstance();
		if ( !tFactory.getFeature(SAXSource.FEATURE) || !tFactory.getFeature(SAXResult.FEATURE) ) {
			System.err.println("Missing features in the XML implementation of the JVM");
			System.exit(1);
		}
		if (args.length < 2) {
			System.err.println("Usage: java "+XSLTPipe.class.getName()+" xslt1 [xslt2 ...] input");
			System.exit(1);
		}

		// http://www.stylusstudio.com/xsllist/200308/post80450.html
		SAXTransformerFactory saxTFactory = (SAXTransformerFactory) tFactory;

		TransformerHandler trans[] = new TransformerHandler[args.length-1];
		for(int i=0; i<trans.length; i++) {
			TransformerHandler t = saxTFactory.newTransformerHandler(new StreamSource(new File(args[i])));
			trans[i] = t;
			if (i > 0) {
				trans[i-1].setResult(new SAXResult(t));
			}
		}

		// Pipe output
		trans[trans.length-1].setResult(new StreamResult(System.out));

		// Feed the pipe
		XMLReader reader = XMLReaderFactory.createXMLReader();
		reader.setContentHandler(trans[0]);
		reader.setProperty("http://xml.org/sax/properties/declaration-handler", trans[0]);
		reader.setProperty("http://xml.org/sax/properties/lexical-handler", trans[0]);
		reader.parse(new InputSource(new FileInputStream(args[args.length-1])));
	}
}

// vim:set ts=4 sw=4 sts=4:
